package com.dingxin.ship_together_api.config.exception;

import cn.dev33.satoken.util.SaResult;
import com.dingxin.ship_together_api.entity.SysErrorLog;
import com.dingxin.ship_together_api.mapper.SysErrorLogMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Arrays;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @Autowired
    private SysErrorLogMapper sysErrorLogMapper;


    // 全局异常拦截 
    @ExceptionHandler
    public SaResult handlerException(Exception e) {
            CompletableFuture.runAsync(()->saveToDB(e));
            e.printStackTrace();
        return SaResult.error(e.getMessage());
    }
    /**
     * 自定义异常处理器
     * @param e
     * @return
     */
    @ExceptionHandler(CustomException.class)
    @ResponseBody
    public SaResult returnMyCustomException(CustomException e) {
        log.error(e.getCode()+" "+e.getMsg());
        CompletableFuture.runAsync(()->saveToDB(e));
        return SaResult.code(e.getCode()).setMsg(e.getMsg());
    }

    /**
     * 处理参数校验异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public SaResult handleMethodArgumentNotValidException(MethodArgumentNotValidException exception) {
        return SaResult.error(Objects.requireNonNull(exception.getBindingResult().getFieldError()).getDefaultMessage());
    }

    /**
     * 保存业务异常入库
     * @param e
     */
    void saveToDB(CustomException e){
        StringBuilder sb = new StringBuilder();
        Arrays.stream(e.getStackTrace()).forEach(item-> sb.append(item).append("\n"));
        SysErrorLog sysErrorLog = new SysErrorLog();
        sysErrorLog.setCode(e.getCode().toString());
        sysErrorLog.setMsg(e.getMsg());
        sysErrorLog.setStacktrace(sb.toString());
        sysErrorLogMapper.insert(sysErrorLog);
    }

    /**
     * 其他异常入库
     * @param e
     */
    void saveToDB(Exception e){
        StringBuilder sb = new StringBuilder();
        Arrays.stream(e.getStackTrace()).forEach(item-> sb.append(item).append("\n"));
        SysErrorLog sysErrorLog = new SysErrorLog();
        sysErrorLog.setMsg(e.getClass().getName()+":"+e.getMessage());
        sysErrorLog.setStacktrace(sb.toString());
        sysErrorLogMapper.insert(sysErrorLog);
    }
}

